package com.coin.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.alicloud.sms.ISmsService;
import com.aliyuncs.dysmsapi.model.v20170525.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coin.domain.Sms;
import com.coin.mapper.SmsMapper;
import com.coin.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * @author 李力
 * @description 针对表【sms(短信信息)】的数据库操作Service实现
 * @createDate 2025-06-07 10:16:53
 */
@Service
public class SmsServiceImpl extends ServiceImpl<SmsMapper, Sms>
        implements SmsService {

    @Autowired
    private ISmsService iSmsService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * @Description: 发送短信
     * @Author: 李 力
     * @Date: 2025/6/11
     * @Param:
     * @return: R
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendMsg(Sms sms) {
        //参数校验略过
        if (sms == null) {
            throw new RuntimeException("参数为空");
        }
        //发送短信
        // send(sms);
        //存入数据库
        sms.setStatus(1);
        return save(sms);
    }

    private boolean send(Sms sms) {
        try {
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            sendSmsRequest.setPhoneNumbers(sms.getMobile()); //发送给谁
            sendSmsRequest.setSignName("数字交易系统"); // 设置签名
            sendSmsRequest.setTemplateCode("SMS_204751106"); // 模板的Code--动态改变
            String code = RandomUtil.randomNumbers(6);
            sendSmsRequest.setTemplateParam("{\"code\":\"" + code + "\"}");
            redisTemplate.opsForValue().set("SMS:" + sms.getTemplateCode() + ":" + sms.getMobile(), code, 1, TimeUnit.MINUTES);
            SendSmsResponse sendSmsResponse = iSmsService.sendSmsRequest(sendSmsRequest);
            String result = sendSmsResponse.getCode();
            return "OK".equals(result);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }
}




